package com.pan.service.aspect;

import com.pan.entity.Result;
import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.ServiceException;
import com.pan.tools.RedisTools;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
public class UseCouponAspect {
    @Resource
    private RedisTools redisTools;

    @Pointcut("execution(public com.pan.entity.Result com.pan.service.impl.UserCouponServiceImpl.receiveCoupon(java.lang.String,java.lang.Long))")
    public void receiveCouponCut(){}

    @Pointcut("execution(public com.pan.entity.Result com.pan.service.impl.UserCouponServiceImpl.selectByUser(java.lang.String))")
    public void selectByUserCut(){}

    @Pointcut("execution(public com.pan.entity.Result com.pan.service.impl.UserCouponServiceImpl.useCoupon(java.lang.String,java.lang.Long,java.lang.Long))")
    public void useCouponCut(){}

    public void checkLogin(String userTicket){
        Result<Boolean> isUserResult = redisTools.exists("user:"+userTicket);
        if (!isUserResult.getData()){
            throw new ServiceException(ErrorCode.NOT_LOGIN);
        }
    }

    @Before("receiveCouponCut()")
    public void  receiveCouponBefore(JoinPoint joinPoint){
//        String userTicket = (String) joinPoint.getArgs()[0];
//        checkLogin(userTicket);
    }

    @Before("selectByUserCut()")
    public void selectByUserBefore(JoinPoint joinPoint){
        String userTicket = (String) joinPoint.getArgs()[0];
        checkLogin(userTicket);
    }


    @Before("useCouponCut()")
    public void useCouponBefore(JoinPoint joinPoint){
        String userTicket = (String) joinPoint.getArgs()[0];
        checkLogin(userTicket);
    }

}
